package com.jic.member.impl;
import	java.util.ArrayList;

import java.lang.Long;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.enums.RedisKey;
import com.jic.order.rest.request.ShoppingCartDeleteRequest;
import com.jic.order.rest.request.ShoppingCartDeleteSubRequest;
import com.jic.order.api.ShoppingCartFeign;
import com.jic.manager.api.manage.SysDeptApi;
import com.jic.manager.api.rest.ManagerStoreApi;
import com.jic.manager.request.SysDeptRequest;
import com.jic.manager.response.MemStoreResponse;
import com.jic.manager.response.SysDeptResponse;
import com.jic.member.api.rest.MemberGrowthOperationApi;
import com.jic.member.common.util.BeanUtil;
import com.jic.member.entity.MemberFavorite;
import com.jic.member.entity.MememberUser;
import com.jic.member.mapper.MemberFavoriteMapper;
import com.jic.member.mapper.MememberUserMapper;
import com.jic.member.request.*;
import com.jic.member.service.MemberFavoriteService;

import com.jic.member.service.MememberActionNewService;
import com.jic.order.rest.request.ShoppingCartDeleteRequest;
import com.jic.order.rest.request.ShoppingCartDeleteSubRequest;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.response.ProductAfterInfoByIdResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 会员收藏信息表
 * @author : mj
 * @email :
 * @since : 2020-01-13 04:22:35
 * @version : v1.0.0
 */
@Service
@Slf4j
public class MemberFavoriteServiceImpl implements MemberFavoriteService{

    @Resource
    private MemberFavoriteMapper memberFavoriteMapper;
    @Autowired
    private RedisClientTemplate redisClientTemplate;
    @Resource
    private ProductListApi productListApi;
    @Resource
    private ManagerStoreApi managerStoreApi;
    @Resource
    private SysDeptApi sysDeptApi;
    @Resource
    private MemberGrowthOperationApi meberGrowthOperationApi;
    @Resource
    private MememberActionNewService mememberActionNewService;
    @Resource
    private ShoppingCartFeign shoppingCartFeign;
    @Resource
    private MememberUserMapper mememberUserMapper;


    @Override
    public long insert(MemberFavorite memberFavorite) {
        long flag = memberFavoriteMapper.insert(memberFavorite);
        return flag;
    }

    @Override
    public long delete(MemberFavorite memberFavorite) {
        return memberFavoriteMapper.delete(memberFavorite);
    }

    @Override
    public long update(MemberFavorite memberFavorite) {
        return memberFavoriteMapper.update(memberFavorite);
    }

    @Override
    public MemberFavorite queryByPrimaryKey(Long id){
        return memberFavoriteMapper.queryByPrimaryKey(id);
    }

    @Override
    public List<MemberFavorite> query(MemberFavorite memberFavorite){
        return memberFavoriteMapper.query(memberFavorite);
    }

    @Override
    public PageResult<MemberFavorite> queryPage(MemberFavoriteRequest memberFavoriteRequest, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<MemberFavorite> list = memberFavoriteMapper.queryPage(startIndex, pageQuery.getLimit(), memberFavoriteRequest);
        long count = memberFavoriteMapper.queryPageCount(memberFavoriteRequest);
        list.forEach(item -> {
            if(null != item.getMemberId()){
                MememberUser mememberUser = mememberUserMapper.queryByPrimaryKey(item.getMemberId());
                if (null != mememberUser){
                    item.setUsername(mememberUser.getNickName());
                }
            }
        });
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public long queryPageCount(MemberFavoriteRequest memberFavoriteRequest) {
        long count = memberFavoriteMapper.queryPageCount(memberFavoriteRequest);
        return count;
    }

    @Override
    public RestResult memberCollects(MemberFavoriteRestRequest form) {
        RestResult rusult = new RestResult();
        MemberFavorite memberFavorite = BeanUtil.copy(form, MemberFavorite.class);
        MemberFavorite delete = new MemberFavorite();
        String userStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + form.getToken());
        if (StringUtils.isEmpty(userStr)) {
            return RestResult.error("4000", "登录失效");
        }
        MememberUser mMember = JSONArray.parseObject(userStr, MememberUser.class);
        memberFavorite.setMemberId(mMember.getId());
        memberFavorite.setUsername(mMember.getName());
//        Long[] collectIds = form.getCollectIds();
        List<StoreInfo> storeInfo = form.getStoreInfo();

        List<ShoppingCartDeleteSubRequest> shoppingCartDeleteList =new ArrayList<> ();

        // 类型 0:取消收藏; 1:收藏
        if (form.getType() == 0) {
            for (int i = 0; i < form.getCollectIds().size(); i++) {
                delete.setEntityId(form.getCollectIds().get(i));
                delete.setMemberId(mMember.getId());
                memberFavoriteMapper.delete(delete);
            }

        } else if (form.getType() == 1) {
            for (int i = 0; i < storeInfo.size(); i++) {
                List<String> goodsIdList = new ArrayList<>();
                for (int j = 0; j < storeInfo.get(i).getCollectIds().length; j++) {
                    memberFavorite.setDeptId(storeInfo.get(i).getStoreId());
                    memberFavorite.setEntityId(storeInfo.get(i).getCollectIds()[j]);
                    MemberFavorite favorite =new MemberFavorite();
                    favorite.setDeleteFlag(0L);
                    favorite.setMemberId(mMember.getId());
                    favorite.setEntityId(storeInfo.get(i).getCollectIds()[j]);
                    favorite.setDeptId(storeInfo.get(i).getStoreId());
                    goodsIdList.add(storeInfo.get(i).getCollectIds()[j].toString());
                    List<MemberFavorite> result = memberFavoriteMapper.query(favorite);
                    if(CollectionUtils.isNotEmpty(result)){
                        continue;
                    }
                    memberFavoriteMapper.insert(memberFavorite);
                }

                ShoppingCartDeleteSubRequest shoppingCartDeleteSubRequest =new ShoppingCartDeleteSubRequest();
                shoppingCartDeleteSubRequest.setGoodsIdList(goodsIdList);
                shoppingCartDeleteSubRequest.setShoppingCardChildrenId(storeInfo.get(i).getStoreId().toString());
                shoppingCartDeleteList.add(shoppingCartDeleteSubRequest);
            }
            //如果没有购物车id 则不调用 删除购车
            if (StringUtils.isNotEmpty(form.getShoppingCartId())){
                //调用购物车删除接口
                ShoppingCartDeleteRequest shopDelete = new ShoppingCartDeleteRequest();
                shopDelete.setShoppingCartDeleteSubRequests(shoppingCartDeleteList);
                shopDelete.setToken(form.getToken());
                shopDelete.setShoppingCartId("80772020082114325600013000001");
                RestResult<Boolean> deleteResult = shoppingCartFeign.delete(shopDelete);
            }
            //调用成长值接口
//            ObtainOrConsumptionGrowthRequest growthRequest = new ObtainOrConsumptionGrowthRequest();
//            growthRequest.setMemberId(String.valueOf(mMember.getId()));
//            growthRequest.setActionType(3L);
//            growthRequest.setObtainMode(String.valueOf(8));
//            RestResult<Boolean> growthResult = meberGrowthOperationApi.obtainOrConsumptionGrowth(growthRequest);

            //调用积分接口
//            MemberIntegralRestRequest integralRequest = new MemberIntegralRestRequest();
//            integralRequest.setObtainMode(8);
//            integralRequest.setUserId(mMember.getId());
//            integralRequest.setChangeTypes(1);
//            RestResult<?> restResult = mememberActionNewService.addMemberIntegralInfoNew(integralRequest);
        }
        rusult.setMsg("操作成功");
        rusult.setCode("0000");
        return rusult;
    }

    @Override
    public RestResult addCollects(MemberFavoriteRestRequest form) {
        RestResult rusult = new RestResult();
        // 校验是否登录
        String userStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + form.getToken());
        if (StringUtils.isEmpty(userStr)) {
            return RestResult.error("4000", "登录失效");
        }
        if (form.getType() == null || CollectionUtils.isEmpty(form.getCollectIds())){
            log.error("addCollects is param is null");
            return RestResult.error("9999","必传参数为空");
        }
        MememberUser mMember = JSONArray.parseObject(userStr, MememberUser.class);

        // 取消收藏
        if (form.getType() == 0){
            // 批量取消收藏
            memberFavoriteMapper.batchUpdate(form.getCollectIds(), mMember.getId());
        }else {
            List<MemberFavorite> memberFavorites = Lists.newArrayList();
            form.getCollectIds().forEach(item ->{
                MemberFavorite favorite =new MemberFavorite();
                favorite.setMemberId(mMember.getId());
                favorite.setEntityId(item);
                favorite.setEntityName(form.getEntityName());
                favorite.setEntityType(form.getEntityType());
                memberFavorites.add(favorite);
            });
            memberFavoriteMapper.batchInsert(memberFavorites);
        }
        rusult.setMsg("操作成功");
        rusult.setCode("0000");
        return RestResult.success(rusult);
    }

    @Override
    public RestResult queryCollectionsPage(MemberFavoriteRestRequest form) {
        RestResult restResult = new RestResult<>();
        Page page = new Page();
        page.setLimit(form.getLimit());
        page.setStart(form.getStart());
        MemberFavoriteRequest memberFavoriteRequest = BeanUtil.copy(form, MemberFavoriteRequest.class);
        String userStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + form.getToken());
        if (!StringUtils.isNotEmpty(userStr)){
            return RestResult.error("4000","登录失效");
        };
        MememberUser mMember = JSONArray.parseObject(userStr, MememberUser.class);
        memberFavoriteRequest.setMemberId(mMember.getId());

        memberFavoriteRequest.setEntityType(form.getType());
        PageResult<MemberFavorite> result = this.queryPage(memberFavoriteRequest, page);
        List<MemberFavorite> memberFavoriteResponseList = result.getRows().stream().map(temp -> {
            MemberFavorite MemberFavorite = BeanUtil.copy(temp, MemberFavorite.class);
            return MemberFavorite;
        }).filter(item -> item != null).collect(Collectors.toList());
        if(form.getType() == 1){
            for(MemberFavorite memberFavoriteRestResponse:memberFavoriteResponseList){
                RestResult<ProductAfterInfoByIdResponse> proInfo = productListApi.queryProductInfoById(memberFavoriteRestResponse.getEntityId());
                if(proInfo.getData()!=null){
                    memberFavoriteRestResponse.setMarketPrice(proInfo.getData().getSalePriceWithTax());
                    memberFavoriteRestResponse.setEntityImg(proInfo.getData().getPictureUrl());
                }
            }
        }else if(form.getType()== 2){
            for(MemberFavorite memberFavoriteRestResponse:memberFavoriteResponseList){
                RestResult<MemStoreResponse> storeInfo = managerStoreApi.getStoreInfo(memberFavoriteRestResponse.getEntityId());
                if(storeInfo.getData()!=null){
                    memberFavoriteRestResponse.setEntityImg(String.valueOf(storeInfo.getData().getStoreLogo()));
                }
            }
        }
        PageResult<MemberFavorite> pageResult = new PageResult<>();
        pageResult.setRows(memberFavoriteResponseList);
        pageResult.setTotal(result.getTotal());
        restResult=RestResult.success(pageResult);
        return restResult;
    }

    @Override
    public RestResult queryFollowersByDeptId(MemberFavoriteRestRequest memberFavoriteRestRequest) {
        SysDeptRequest sysDeptRequest =new SysDeptRequest();
        sysDeptRequest.setId(memberFavoriteRestRequest.getDeptId());
        Long followers =0L;
        List<SysDeptResponse> result = sysDeptApi.query(sysDeptRequest);
        if(CollectionUtils.isNotEmpty(result)){
            Long businessId = result.get(0).getBusinessId();
            Integer entityType = 2;
             followers = memberFavoriteMapper.queryFollowersByDeptId(businessId,entityType);
        }
        return RestResult.success(followers);
    }

    @Override
    public Boolean queryFollowersByEntityId(MemberFavoriteRestRequest memberFavoriteRestRequest) {
        Boolean flag = false;
        MemberFavorite followers =new MemberFavorite();
        followers.setEntityId(memberFavoriteRestRequest.getEntityId());
        followers.setMemberId(memberFavoriteRestRequest.getMemberId());
        followers.setDeleteFlag(0L);
        List<MemberFavorite> query = memberFavoriteMapper.query(followers);
        if(CollectionUtils.isNotEmpty(query)){
            flag=true;
        }
        return flag;
    }

    @Override
    public RestResult countFollowersByEntityId(MemberFavoriteRestRequest memberFavoriteRestRequest) {
        Long followers =0L;
        Integer entityType = 2;
        MemberFavoriteRequest memberFavoriteRequest = BeanUtil.copy(memberFavoriteRestRequest, MemberFavoriteRequest.class);
        followers = memberFavoriteMapper.countFollowersByEntityId(memberFavoriteRequest);
        return RestResult.success(followers);
    }

}
